<template>
  <el-card>
    <div slot="header" class="clearfix">
      <span>公会公告</span>
    </div>
    <!-- 新增/编辑公告对话框 -->
    <el-dialog
        title="公告操作"
        v-model="dialogVisible"
        width="30%"
    >
      <el-form
          ref="noticeForm"
          :model="editNotice"
          label-width="100px"
      >
        <el-form-item label="标题">
          <el-input
              v-model="editNotice.title"
              placeholder="请输入标题"
          />
        </el-form-item>
        <el-form-item label="内容">
          <el-input
              type="textarea"
              v-model="editNotice.content"
              placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
              @click="dialogVisible = false"
          >
            取 消
          </el-button>
          <el-button
              type="primary"
              @click="submitEditedNotice"
          >
            {{ editNotice.id ? '更新' : '发布' }}公告
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-mask">
      <el-loading-spinner></el-loading-spinner>
      <p>加载中...</p>
    </div>

    <!-- 公告列表表格 -->
    <el-table
        :data="notices"
        style="width: 100%; margin-top: 20px;"
        v-else
    >
      <el-table-column
          prop="id"
          label="公告ID"
          width="100"
      />
      <el-table-column
          prop="title"
          label="标题"
      />
      <el-table-column
          prop="publishTime"
          label="发布时间"
      />
      <el-table-column
          label="操作"
          width="150"
      >
        <template #default="scope">
          <el-button
              @click="editNoticeItem(scope.row)"
              size="small"
          >
            编辑
          </el-button>
          <el-button
              @click="deleteNotice(scope.row.id)"
              type="danger"
              size="small"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态提示 -->
    <div v-if="notices.length === 0 && !loading" class="empty-state">
      <img src="https://picsum.photos/200/150" alt="Empty" />
      <p>暂无公告数据</p>
      <el-button
          type="primary"
          @click="showAddNoticeDialog"
      >
        新增公告
      </el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import {
  publishGuildNotice,
  getAllGuildNotices,
  deleteGuildNotice,
  updateGuildNotice
} from '@/utils/requests.js';
import { ElMessage } from 'element-plus';

// 状态管理
const notices = ref([]);
const dialogVisible = ref(false);
const editNotice = ref({
  id: null,
  title: '',
  content: '',
  publishTime: ''
});
const loading = ref(false);

// 获取公告列表
const loadNotices = async () => {
  loading.value = true;
  try {
    const response = await getAllGuildNotices();
    console.log('接口返回数据:', response);

    // 处理接口返回数据，确保notices为数组
    if (response && response.data) {
      notices.value = Array.isArray(response.data) ? response.data : [];
      if (notices.value.length === 0) {
        ElMessage.info('暂无公告数据');
      }
    } else {
      notices.value = [];
      ElMessage.warning('获取公告列表失败，返回数据为空');
    }
  } catch (error) {
    console.error('获取公会公告出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
    notices.value = []; // 确保notices始终为数组
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadNotices();
});

// 新增公告
const showAddNoticeDialog = () => {
  dialogVisible.value = true;
  editNotice.value = {
    id: null,
    title: '',
    content: '',
    publishTime: ''
  };
};

// 编辑公告
const editNoticeItem = (row) => {
  editNotice.value = { ...row };
  dialogVisible.value = true;
};

// 提交编辑/新增公告
const submitEditedNotice = async () => {
  // 简单表单验证
  if (!editNotice.value.title) {
    ElMessage.warning('请输入公告标题');
    return;
  }
  if (!editNotice.value.content) {
    ElMessage.warning('请输入公告内容');
    return;
  }

  try {
    let response;
    if (editNotice.value.id) {
      // 更新公告
      response = await updateGuildNotice(editNotice.value);
    } else {
      // 发布新公告
      response = await publishGuildNotice(editNotice.value);
    }

    if (response && response.code === 200) {
      ElMessage.success(
          editNotice.value.id ? '更新公告成功' : '发布公告成功'
      );
      await loadNotices(); // 刷新列表
      dialogVisible.value = false;
    } else {
      ElMessage.error(
          editNotice.value.id
              ? '更新公告失败: ' + (response?.message || '未知错误')
              : '发布公告失败: ' + (response?.message || '未知错误')
      );
    }
  } catch (error) {
    console.error('提交公告出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 删除公告
const deleteNotice = async (id) => {
  if (confirm('确定要删除该公告吗？此操作不可撤销！')) {
    try {
      const response = await deleteGuildNotice(id);
      if (response && response.code === 200) {
        ElMessage.success('删除公告成功');
        await loadNotices(); // 刷新列表
      } else {
        ElMessage.error('删除公告失败: ' + (response?.message || '未知错误'));
      }
    } catch (error) {
      console.error('删除公告出错:', error);
      ElMessage.error('网络请求失败，请检查控制台日志');
    }
  }
};
</script>

<style scoped>
.loading-mask {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
  color: #999;
}

.empty-state img {
  width: 200px;
  height: 150px;
  object-fit: cover;
  margin-bottom: 20px;
  opacity: 0.6;
}

.empty-state p {
  margin-bottom: 20px;
}
</style>